﻿
import wsgiref.handlers
import os
import cgi

import decoder
import primes

from google.appengine.ext.webapp import template
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from django.utils import simplejson
from google.appengine.ext import db

maxFieldCode = 999

		
class MainPage(webapp.RequestHandler):
	def get(self):
		model = {
			'greetings': 'holitas'
		}
		
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, model))
	
	#Find the best set of 3 factors that is not used
	def getFactors(self, wheelName, fieldCounts):
			
		factors = []
		for count in fieldCounts:
			factors.append(self.getBestFactor(count))
		

		
		while True:
			query = db.Query(Wheel)
			query.filter('factor0 = ', factors[0]).filter('factor1 = ', factors[1]).filter('factor2 = ', factors[2])
			if query.count() == 0 : break
			maxFactor = max(factors)
			factors[factors.index(maxFactor)] = primes.Primes.findFirstSmallerThan(maxFactor)
			
		return factors
		

	def getBestFactor(self, count):
		factorCeiling = maxFieldCode/count
		return primes.Primes.findFirstSmallerThan(factorCeiling)		


		
			
	def post(self):
		wheelName = self.request.get('wheelName')
		
		fieldValues0 = self.request.get('fieldValues0').split(',')
		fieldValues1 = self.request.get('fieldValues1').split(',')
		fieldValues2 = self.request.get('fieldValues2').split(',')
		
		factors = self.getFactors(wheelName, [len(fieldValues0), len(fieldValues1), len(fieldValues2)])

		wheel = Wheel(name=wheelName, factor0=factors[0], factor1=factors[1], factor2=factors[2])
		wheel.put()
		
		self.saveRowValues(wheel, 0, self.request.get('fieldLabel0'), fieldValues0)
		self.saveRowValues(wheel, 1, self.request.get('fieldLabel1'), fieldValues1)
		self.saveRowValues(wheel, 2, self.request.get('fieldLabel2'), fieldValues2)
		
		path = os.path.join(os.path.dirname(__file__), 'index.html')
		self.response.out.write(template.render(path, {'wheelName' : wheelName,
														'wheelFactors': factors}))
	
	def saveRowValues(self, wheel, index, label, fieldValues):
		valueIndex = 0
				
		for value in fieldValues:
			valueIndex = valueIndex + 1
			row = WheelRow(wheel = wheel, 
							fieldIndex = index,
							fieldLabel = label,
							fieldValue = value, 
							fieldCode = valueIndex * 23)
			row.put()
	
class WheelController(webapp.RequestHandler):
	def get(self):
		wheelName = self.request.get('wheelName')
		
		jsonData = [ {
						'name': '',
						'values': [],
						'codes': []
					}, 
					{
						'name': '',
						'values': [],
						'codes': []
					}, 
					{
						'name': '',
						'values': [],
						'codes': []
					}]
					
		query = db.Query(WheelRow)
		query.filter('name =', wheelName).order('fieldCode')
		
		for row in query:
			jsonData[row.fieldIndex]['name'] = row.fieldLabel
			jsonData[row.fieldIndex]['values'].append(row.fieldValue)
			jsonData[row.fieldIndex]['codes'].append(row.fieldCode)		
		
		self.response.headers['Content-Type'] = 'application/json'			
		self.response.out.write(simplejson.dumps(jsonData))

class Wheel(db.Model):
	name = db.StringProperty(required=True)
	factor0 = db.IntegerProperty(required=True)
	factor1 = db.IntegerProperty(required=True)
	factor2 = db.IntegerProperty(required=True)	
	
class WheelRow(db.Model):
	wheel = db.ReferenceProperty(Wheel)
	fieldIndex = db.IntegerProperty(required=True)
	fieldLabel = db.StringProperty(required=True)
	fieldValue = db.StringProperty(required=True)	
	fieldCode = db.IntegerProperty(required=True)		

application = webapp.WSGIApplication([('/', MainPage),
										('/wheel', WheelController),
										('/decoder', decoder.Decoder)],
                                       debug=True)

def main():
	run_wsgi_app(application)


if __name__ == '__main__':
  main()
